package cn.accp.accpmis.dao.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import cn.accp.accpmis.dao.ConfigDao;
import cn.accp.accpmis.entity.Config;

public class FileConfigDao implements ConfigDao {
	private File file;
	private Config config;

	@Override
	public Config getConfig() {
		return readConfig();
	}

	@Override
	public boolean setConfig(Config config) {
		this.config = config;
		return writeConfig();
	}

	public FileConfigDao() {
		String fileName = "config.sys";
		String dir = this.getClass().getClassLoader().getResource("").getPath();
		this.file = new File(dir, fileName);
	}

	private boolean writeConfig() {
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		String inpuString;
		OutputStreamWriter ws = null;
		BufferedWriter bw = null;
		try {
			ws = new OutputStreamWriter(new FileOutputStream(file));
			bw = new BufferedWriter(ws);
			inpuString = "company=" + config.getCompanyName();
			bw.write(inpuString);
			bw.newLine();
			inpuString = "phone=" + config.getPhoneNumber();
			bw.write(inpuString);
			bw.newLine();
			inpuString = "address=" + config.getAddress();
			bw.write(inpuString);
			bw.flush();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				ws.close();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private Config readConfig() {
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return config;
			}
		}
		String line;
		InputStreamReader inStream = null;
		BufferedReader br = null;
		try {
			inStream = new InputStreamReader(new FileInputStream(file));
			br = new BufferedReader(inStream);
			config = new Config();
			line = br.readLine();
			if (line != null) {
				config.setCompanyName(line.split("=")[1]);
			}
			line = br.readLine();
			if (line != null) {
				config.setPhoneNumber(Integer.parseInt(line.split("=")[1]));
			}
			line = br.readLine();
			if (line != null) {
				config.setAddress(line.split("=")[1]);
				return config;
			} else {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				inStream.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
